package io.renren.common.interceptor;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import io.renren.common.constant.Dict;
import io.renren.common.exception.RenException;
import io.renren.common.redis.RedisService;
import io.renren.common.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class IPInterceptor implements HandlerInterceptor {
	@Autowired
    private RedisService redisService;
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        System.out.println("请求地址："+url);
        //过滤ip,若用户在白名单内，则放行
    	System.err.println(request.getRequestURI());
    	if(request.getRequestURI().equals("/admin/login")){
	   		 String ipAddress=IpUtils.getIpAddr(request);
	      	 log.info("当前登陆的IP:"+ipAddress);
	         Set<String> hashSet = redisService.getHashSet(Dict.IPADDRESSSET);
	         if(!hashSet.contains(ipAddress))
	        	 throw new RenException("当前IP不允许登录");
    	}
		return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}